package cn.wyj.service.impl;

import cn.wyj.dao.ArticleMapper;
import cn.wyj.dao.CommentMapper;
import cn.wyj.dao.StatisticMapper;
import cn.wyj.domain.Article;
import cn.wyj.domain.Comment;
import cn.wyj.domain.StaticticsBo;
import cn.wyj.domain.Statistic;
import cn.wyj.service.SiteService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
@Transactional
public class SiteServiceImpl implements SiteService {

    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private StatisticMapper statisticMapper;

    @Override
    public List<Comment> recentComments(Integer count) {
        PageHelper.startPage(1,count<1?10:count);
        List<Comment> newComment = commentMapper.findNewComment();
        return newComment;
    }

    @Override
    public List<Article> recentArticles(Integer count) {
        PageHelper.startPage(1,count<1?10:count);
        List<Article> articles = articleMapper.findByPage();
        for(int i =0;i<articles.size();i++){
            Statistic statistic = statisticMapper.findStatisticByArticleId(articles.get(i).getId());
            articles.get(i).setHits(statistic.getHits());
            articles.get(i).setCommentsNum(statistic.getCommentsNum());
        }
        return articles;
    }

    @Override
    public StaticticsBo getStatistic() {
        StaticticsBo staticticsBo = new StaticticsBo();
        Integer totalComment = commentMapper.getTotalComment();
        Integer articleCount = articleMapper.getArticleCount();
        staticticsBo.setArticles(articleCount);
        staticticsBo.setComments(totalComment);
        return staticticsBo;
    }

    @Override
    public void updateStatistic(Article article) {
        Statistic statistic = statisticMapper.findStatisticByArticleId(article.getId());
        statistic.setHits(statistic.getHits()+1);
        statisticMapper.updateArticleHitsByArticleId(article.getId());
    }
}
